from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from meiduo_mall_admin.my_paginate import MyPageNumberPagination
from goods.models import SKUImage, SKU
from . import sku_image_serializers
from django.conf import settings


class SKUImageViews(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = sku_image_serializers.SKUImageSerializer
    queryset = SKUImage.objects.all()

    def simple(self, request):
        skus = SKU.objects.all()
        serializer = sku_image_serializers.SKUSerializer(instance=skus, many=True)
        return Response(serializer.data)

    # 通用的功能没有上传图片的功能,所有要重写
    def create(self, request, *args, **kwargs):
        # 获取参数
        image = request.FILES.get("image")
        sku_id = request.data.get("sku")
        # 校验参数
        if not image:
            return Response(status=403)
        # 上传入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(image.read())
        print(ret)
        # 判断是否上传成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        image_url = ret.get("Remote file_id")
        SKUImage.objects.create(sku_id=sku_id, image=image_url)
        SKU.objects.filter(id=sku_id, default_image_url='').update(default_image_url=image_url)

        return Response(status=201)

    # 修改图片
    def update(self, request, *args, **kwargs):
        # 获取参数
        image = request.FILES.get("image")  # 新增的图片的对象
        sku_id = request.data.get("sku")    # sku_id
        sku_image = self.get_object()       # 旧图片的对象
        # 校验参数
        if not all([image, sku_id, sku_image]):
            return Response(status=400)
        # 上传入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(image.read())
        # 判断是否上传成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)
        # 数据入库
        image_url = ret.get("Remote file_id")
        SKUImage.objects.filter(id=sku_image.id).update(sku_id=sku_id, image=image_url)

        return Response(status=200)
